import 'package:flutter/material.dart';
import 'package:flutter_base/page/common/smart_refresh_widget.dart';
import 'package:flutter_base/viewmodel/knowledge/knowledge_detail_vm.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../utils/navigator_utils.dart';
import '../../common/webview_page.dart';
import '../../common/webview_widget.dart';

///
/// @DIR_PATH：lib/viewmodel/knowledge
/// @TIME：2024/6/13 15:13
/// @AUTHOR：starr
///
class KnowledgeTabChildPage extends StatefulWidget{
  const KnowledgeTabChildPage({super.key,this.treeId});
  final int? treeId;

  @override
  State<StatefulWidget> createState()  => KnowledgeTabChildState();

}

class KnowledgeTabChildState extends State<KnowledgeTabChildPage>{
  KnowledgeDetailViewModel viewModel = KnowledgeDetailViewModel();

  RefreshController controller = RefreshController();

  @override
  void initState() {
    super.initState();
    viewModel.getKnowledgeDetail(false, widget.treeId);
  }
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(create: (context){
      return viewModel;
    },child: Scaffold(body: Consumer<KnowledgeDetailViewModel>(builder: (context,vm,child){
      return SmartRefreshWidget(
        onLoading: (){
          refreshOrLoad(true);
        },
        onRefresh: (){
          refreshOrLoad(false);
        },
        controller: controller,
        child: ListView.builder(
          itemCount: vm.itemList.length,
            itemBuilder: (context,index){
                return GestureDetector(
                  onTap: (){
                    NavigatorUtils.openPageByFade(
                        context,
                        WebViewPage(
                          webViewType: WebViewType.URL,
                          loadResource: vm.itemList[index].link ?? "",
                          title: vm.itemList[index].title,
                          showTitle: true,
                        ));
                  },
                  child: Container(
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey),
                      borderRadius: BorderRadius.circular(5),
                    ),
                    padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                    margin: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
                    child: Text(
                      vm.itemList[index].title ?? "",
                      style: const TextStyle(
                          fontSize: 16, fontWeight: FontWeight.bold),
                    ),
                  ),
              );
            }
        )
      );
    })));
  }

  void refreshOrLoad(loadMore){
    viewModel.getKnowledgeDetail(loadMore, widget.treeId).then((value){
      if(loadMore){
        controller.loadComplete();
      }else{
        controller.refreshCompleted();
      }
    });
  }

}